package com.spider.im.common.aspect;

import cn.hutool.json.JSONUtil;
import com.spider.im.common.annotation.IgnoreLog;
import com.spider.im.common.utils.DesensitizationUtils;
import org.apache.commons.lang3.SerializationUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 切面类，用于记录方法的调用和返回结果
 */
@Aspect
@Component
public class LoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    @Around("execution(* com.spider.im..*Controller.*(..))")
    public Object logMethodCallAndReturn(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = signature.getName();
        // 检查是否需要忽略日志
        if (method.isAnnotationPresent(IgnoreLog.class)) {
            return joinPoint.proceed();
        }
//        // 获取方法参数并进行深度复制
//        Object[] args = Arrays.copyOf(joinPoint.getArgs(), joinPoint.getArgs().length);
//        // 对深度复制后的参数进行脱敏
//        for (int i = 0; i < args.length; i++) {
//            if (args[i] != null) {
//                args[i] = DesensitizationUtils.desensitizeNewObject(args[i]);
//            }
//        }

        // 记录开始时间
        long startTime = System.currentTimeMillis();
        Object[] args = joinPoint.getArgs();
        // 使用 Hutool 转换为 JSON 字符串
        String jsonArgs = JSONUtil.toJsonStr(args);
        logger.info("start method: {} with arguments: {}", methodName, jsonArgs);

        // 执行目标方法
        Object result = joinPoint.proceed(joinPoint.getArgs());

        // 获取结束时间
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;

//        // 处理返回结果
//        Object desensitizedResult = result;
//        // 对深度复制后的返回结果进行脱敏
//        if (result != null) {
//            desensitizedResult = DesensitizationUtils.desensitizeNewObject(result);
//        }

        String jsonResult = JSONUtil.toJsonStr(result);
        logger.info("end method: {} with result: {}. Execution time: {} ms", methodName, jsonResult, executionTime);

        return result;
    }

}
